package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取本次请求的URI
        String url = request.getRequestURI();
        log.info("拦截到请求:{}", url);
        //4、判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee")!= null){
            return true;
        }
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        R<String> notlogin = R.error("NOTLOGIN");
        String s = JSONObject.toJSONString(notlogin);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(s);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
